<?php
/**
 * CreateTime: 2022/4/30 16:44
 */

namespace App\Func;

class FormatFunc
{
    /**
     * 获取树类型
     * @param $data
     * @return array
     */
    public static function getTreeByData($data): array
    {
        $tree = [];
        //保存排序后的新数组
        $newData = [];
        //循环重新排列
        foreach ($data as $datum) {
            $newData[$datum['dictionary_id']] = $datum;
        }
        foreach ($newData as $key => $datum) {
            if ($datum['parent_id'] > 0) {
                //不是根节点的将自己的地址放到父级的child节点
                $newData[$datum['parent_id']]['childList'][] = &$newData[$key];
                unset($newData['dictionary_id']);
                unset($newData['parent_id']);
            } else {
                //根节点直接把地址放到新数组中
                $tree[] = &$newData[$datum['dictionary_id']];
            }
        }
        return $tree;
    }
}